<template>
  <div class="add">
    <a-card title="发布产品">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="商品链接" prop="goods_url">
          <a-input v-model="form.goods_url" placeholder="请输入淘宝产品链接后点回车键" @pressEnter="detectiongoods" @blur="detectiongoods"/>
        </a-form-model-item>
        <div v-show="ischeck">
          <a-form-model-item label="产品标题" prop="goods_title">
            <a-input v-model="form.goods_title" />
          </a-form-model-item>
          <a-form-model-item label="推广标题(精简12字以内)" prop="tg_title">
            <a-input v-model="form.tg_title" />
          </a-form-model-item>
          <a-form-model-item label="产品分类" prop="goods_class">
            <a-select v-model="form.goods_class" placeholder="请选择分类">
              <a-select-option :value="item.id" v-for="(item,index) in classList" :key="index">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="店铺名">
            <a-input v-model="form.shop_name" disabled />
          </a-form-model-item>
          <a-form-model-item label="商品图片" prop="goods_img">
            <a-input v-model="form.goods_img" placeholder="请输入商品图片地址或自行上传" />
            <a-upload
              v-if="form.goods_img==''"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadurl"
              :before-upload="beforeUpload"
              @change="handleChange">
              <div>
                <a-icon :type="uploadloading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
            <div
              v-else
              class="img_box">
              <img :src="form.goods_img" alt="" style="width:150px"/>
              <a-icon
                type="close-circle"
                @click="closeimg" />
            </div>
          </a-form-model-item>
          <a-form-model-item label="朋友圈文案" prop="friend_text">
            <editor-bar v-model="form.friend_text" :value="form.friend_text" @change="getEditor" id="weditor">
            </editor-bar>
          </a-form-model-item>
          <a-form-model-item label="优惠劵链接" prop="coupon_url">
            <a-input v-model="form.coupon_url" placeholder="请输入优惠劵链接后点回车键" @pressEnter="checkCouponInfo" @blur="checkCouponInfo" />
          </a-form-model-item>
          <a-form-model-item label="开始时间" prop="activity_start_time">
            <a-date-picker format="YYYY-MM-DD" v-model="form.start_time" @change="startChange" />
            <span style="padding:0 20px;">结束时间:</span>
            <a-date-picker format="YYYY-MM-DD" v-model="form.end_time" @change="endChange" />
          </a-form-model-item>
          <a-form-model-item label="优惠劵总数">
            <a-input v-model="form.coupon_num" style="width: 200px" disabled>
              <span slot="addonAfter">张</span>
            </a-input>
            <span style="padding:0 20px;">优惠劵剩余:</span>
            <a-input v-model="form.coupon_surplus" style="width: 200px" disabled>
              <span slot="addonAfter">张</span>
            </a-input>
            <span style="padding:0 20px;">优惠券门槛金额:</span>
            <a-input v-model="form.single_sum" style="width: 200px" disabled>
              <span slot="addonAfter">元</span>
            </a-input>
            <span style="padding:0 20px;">优惠劵金额:</span>
            <a-input v-model="form.coupon_money" style="width: 200px" disabled>
              <span slot="addonAfter">元</span>
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="原价">
            <a-input v-model="form.price" style="width: 200px" disabled>
              <span slot="addonAfter">元</span>
            </a-input>
            <span style="padding:0 20px;">券后价:</span>
            <a-input v-model="form.after_price" style="width: 200px">
              <span slot="addonAfter">元</span>
            </a-input>
            <span style="padding:0 20px;">抵扣价(默认计算不会低于0):</span>
            <a-input v-model="form.zk_price" style="width: 200px" disabled>
              <span slot="addonAfter">元</span>
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="拍几件" prop="num">
            <a-input v-model="form.num" style="width: 200px"> </a-input>
          </a-form-model-item>
          <a-form-model-item label="目标销量" prop="target_num">
            <a-input v-model="form.target_num" style="width: 200px"> </a-input>
          </a-form-model-item>
          <a-form-model-item label="产品类型" prop="goods_type">
            <a-radio-group v-model="form.goods_type" @change="typeChange">
              <a-radio :value="item.id" v-for="(item,index) in goodstype" :key="index">
                {{ item.name }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="佣金类型" prop="commission_type">
            <a-radio-group v-model="form.commission_type" @change="cmstypeChange">
              <a-radio :value="1">
                通用
              </a-radio>
              <a-radio :value="2">
                营销
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="佣金率" prop="commission_bl">
            <a-input v-model="form.commission_bl" style="width: 200px">
              <span slot="addonAfter">%</span>
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="服务费" prop="service">
            <a-input v-model="form.service" style="width: 200px">
              <span slot="addonAfter">%</span>
            </a-input>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="onSubmit">
              提交
            </a-button>
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-card>
  </div>
</template>

<script>
import Moment from 'moment'
  import EditorBar from '@/components/Editor/WangEditor'
  import {
    doAddGoods,
    getGoodsType,
    checkGoodsInfo,
    getClassInfo,
    checkCouponInfo
  } from '@/api/goods.js'
  export default {
    name: 'Add',
    components: {
      EditorBar
    },
    data () {
      return {
        uploadurl: 'http://192.168.1.141:8088/api/upload',
        // uploadurl: 'http://tlj-api.letuilm.com/api/upload',
        uploadloading: false,
        imageUrl: '',
        ischeck: true,
        labelCol: {
          span: 4
        },
        wrapperCol: {
          span: 12
        },
        classList: [
          // {
          //   id: 1,
          //   name: '其他'
          // }
        ],
        goodstype: [
          // {
          //   id: 1,
          //   name: '7元档(6元抵扣)'
          // }
        ],
        form: {
          item_id: '',
          goods_url: '',
          goods_title: '',
          tg_title: '',
          goods_class: '',
          shop_name: '',
          shop_id: '',
          goods_img: '',
          month_num: '', // 月销量
          friend_text: '',
          coupon_url: '',
          activity_start_time: '',
          activity_end_time: '',
          start_time: null,
          end_time: null,
          coupon_num: '',
          coupon_surplus: '',
          single_sum: '',
          coupon_money: '',
          num: '',
          price: '',
          after_price: '',
          zk_price: '',
          target_num: '',
          goods_type: 1,
          commission_type: 1,
          commission_bl: '',
          service: ''
        },
        rules: {
          goods_url: [{
            required: true,
            message: '请输入淘宝产品链接!',
            trigger: 'blur'
          }],
          goods_title: [{
            required: true,
            message: '请输入产品标题!',
            trigger: 'blur'
          }],
          goods_img: [{
            required: true,
            message: '请上传商品图片!',
            trigger: 'blur'
          }],
          friend_text: [{
            required: true,
            message: '请填写朋友圈文案!',
            trigger: 'blur'
          }],
          coupon_url: [{
            required: true,
            message: '请输入优惠卷链接!',
            trigger: 'blur'
          }],
          goods_type: [{
            required: true,
            message: '请选择商品类型!',
            trigger: 'change'
          }],
          num: [{
            required: true,
            message: '请输入需要拍几件!',
            trigger: 'blur'
          }],
          start_time: [{
            required: true,
            message: '请选择开始和结束时间!',
            trigger: 'blur'
          }],
          end_time: [{
            required: true,
            message: '请选择开始和结束时间!',
            trigger: 'blur'
          }],
          tg_title: [{
            required: true,
            message: '请输入推广标题!',
            trigger: 'blur'
          }],
          goods_class: [{
            required: true,
            message: '请选择分类!',
            trigger: 'blur'
          }],
          target_num: [{
            required: true,
            message: '请输入目标销量!',
            trigger: 'blur'
          }],
          commission_type: [{
            required: true,
            message: '请输入选择佣金类型!',
            trigger: 'change'
          }],
          commission_bl: [{
            required: true,
            message: '请输入佣金率!',
            trigger: 'blur'
          }],
          service: [{
            required: true,
            message: '请输入服务费率!',
            trigger: 'blur'
          }]
        }
        // info: {
        //   itemId: '', // 商品id
        //   title: '', // 商品标题
        //   images: [], // 主图数组
        //   rootCategoryId: '', // 分类原始id
        //   shopName: '', // 店铺名称
        //   goodRatePercentage: '', // 店铺好评率
        //   priceMoney: '', // 商品原价
        //   evaluates: [] // 店铺评分数组
        // }
      }
    },

    computed: {},
    created () {
      this.getGoodsType()
      this.getClassInfo()
    },
    mounted () {},
    methods: {
      Moment,
      // 优惠卷检测
      checkCouponInfo () {
        // this.form.coupon_url='https://uland.taobao.com/quan/detail?sellerId=725677994&activityId=75bc83cf8948471382a8c9604f323c0a'
        checkCouponInfo({
          item_id: this.form.item_id,
          coupon_url: this.form.coupon_url
        })
        .then(res => {
          if (res.code === 200) {
            console.log('优惠卷返回', res)
            this.form.coupon_money = res.data.money
            this.form.coupon_num = res.data.couponnum
            this.form.coupon_surplus = res.data.couponsurplus
            this.form.single_sum = res.data.single_sum
            this.form.after_price = this.form.price - res.data.money
            this.form.zk_price = this.form.after_price - 6
            this.form.start_time = Moment((res.data.start_time * 1000))
            this.form.end_time = Moment((res.data.end_time * 1000))
          } else {
            this.$message.info(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
      },

      // 获取分类
      getClassInfo () {
        getClassInfo()
        .then(res => {
          if (res.code === 200) {
          // console.log('分类返回', res)
          this.classList = res.data
          } else {
          this.$message.info(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
      },

      // 商品检测
      detectiongoods () {
        // this.form.goods_url =
        //   'https://detail.m.tmall.com/item.htm?id=606540358182&ali_trackid=2:mm_40370965_22602780_74958456:'
        if (this.form.goods_url === '') {
          this.$message.info('请输入商品地址!')
        } else {
          var reg = /id=(\d+)/i // 提取url里id=后面的参数
          this.form.goods_url.match(reg)
          const idArr = this.form.goods_url.match(reg)
          // console.log('商品id', idArr[1], '商品链接', this.form.goods_url)
          this.form.item_id = idArr[1]
          this.$jsonp(
            'https://acs.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?&api=mtop.taobao.detail.getdetail&v=6.0&ttid=2013%40taobao_h5_1.0.0&type=jsonp&dataType=jsonp&data=%7B%22itemNumId%22%3A%22' +
            this.form.item_id +
            // '590515928833' +
            '%22%7D'
          ).then(res => {
            // console.log(res)
              let priceobj = {}
              priceobj = JSON.parse(res.data.apiStack[0].value)
              // console.log('apiStack.value', priceobj)
              // console.log('priceText', priceobj.price.price.priceText)
              if (priceobj.price.price.priceMoney) {
                // this.info.priceMoney = priceobj.price.price.priceMoney / 100
                this.form.price = priceobj.price.price.priceMoney / 100
              } else {
                const pricestr = priceobj.price.price.priceText
                // this.info.priceMoney = pricestr.split('-')[0] // 最低价
               this.form.price = pricestr.split('-')[0] // 最低价
                // this.info.priceMoney = pricestr.split("-")[1];//最高价
              }
              this.form.goods_title = res.data.item.title
              this.form.shop_name = res.data.seller.shopName
              this.form.shop_id = res.data.seller.shopId
              this.form.item_id = res.data.item.itemId
              // console.log('月销量', priceobj.item.sellCount)
              if (/.*[\u4e00-\u9fa5]+.*$/.test(priceobj.item.sellCount)) {
                this.form.month_num = parseInt(priceobj.item.sellCount) * 10000
                // console.log(this.form.month_num)
              } else {
                this.form.month_num = priceobj.item.sellCount
              }
              // this.info.itemId = res.data.item.itemId
              // this.info.title = res.data.item.title
              // this.info.images = res.data.item.images
              // this.info.rootCategoryId = res.data.item.rootCategoryId
              // this.info.shopName = res.data.seller.shopName
              // this.info.goodRatePercentage = res.data.seller.goodRatePercentage
              // this.info.evaluates = res.data.seller.evaluates
              // console.log('info', this.info)
              checkGoodsInfo({
                item_id: this.form.item_id
              }).then(res => {
                // console.log(res)
                if (res.code === 200) {
                  this.$message.success('当前商品可以提交!')
                  this.ischeck = true
                } else {
                  this.$message.info('对不起!当前商品暂无法提交,请更换商品检测!')
                  }
              }).catch(err => {
                console.log(err)
              })
          }).catch(err => {
            console.log(err)
          })
        }
      },
      // 获取产品类型
      getGoodsType () {
        getGoodsType()
          .then(res => {
            if (res.code === 200) {
              // console.log('商品类型返回', res)
              this.goodstype = res.data
            } else {
              this.$message.info(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      },

      typeChange () {
        console.log(this.form.goods_type)
      },
      cmstypeChange () {
        console.log(this.form.commission_type)
      },
      startChange () {
        console.log(this.form.start_time)
      },
      endChange () {
        console.log(this.form.end_time)
      },
      // 获取富文本内容
      getEditor (value) {
        // console.log(value)
        this.form.friend_text = value
      },
      // 上传
      handleChange (info) {
        // console.log(info)
        if (info.file.status === 'uploading') {
          this.loading = true
          return
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.loading = false
          this.form.goods_img = '//' + info.file.response.data.url
        }
      },
       closeimg () {
        this.form.goods_img = ''
      },
      beforeUpload (file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('对不起!请上传jpg或者png格式的图片')
        }
        const isLt2M = file.size / 1024 / 1024 < 5
        if (!isLt2M) {
          this.$message.error('对不起!图片大小不能超过5MB!')
        }
        return isJpgOrPng && isLt2M
      },
      // 提交
      onSubmit () {
        // console.log('submit!', this.form)
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.form.activity_start_time = parseInt(Moment(this.form.start_time).valueOf() / 1000)
            this.form.activity_end_time = parseInt(Moment(this.form.end_time).valueOf() / 1000)
            console.log(this.form)
            doAddGoods(this.form).then(res => {
              // console.log(res)
              if (res.code === 200) {
                this.$message.success('新增成功!')
                this.resetForm()
                this.form = {}
                this.ischeck = false
              } else {
                this.$message.info(res.msg)
              }
            }).catch(err => {
              console.log(err)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm () {
        this.$refs.ruleForm.resetFields()
      }
    }
  }
</script>

<style lang="less" scoped>
  .avatar-uploader>.ant-upload {
    width: 128px;
    height: 128px;
  }

  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
     .img_box {
        position: relative;
        width: 150px;
      }

      // /deep/.ant-upload {
      //   border-radius: 50%;
      //   padding: 0px;
      // }

      .anticon-close-circle {
        position: absolute;
        top: 0;
        right: 0;
        font-size: 20px;
        cursor: pointer;
        display: none;
        z-index: 3;
        color: white;
        transition: all 0.3s linear;
      }

      .img_box:hover {
        .anticon-close-circle {
          display: block;
        }
      }

      .anticon-close-circle:hover {
        display: block;
        transform: rotate(90deg);
      }
</style>
